import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import { setRoutes, resetRoutes } from './setRoutes'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    orgName: '',
    logo: '',
    fba: false,
    orgOwner: false,
    btns: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_PROFILE: (state, profile) => {
    state.logo = profile.logo
    state.name = profile.userName
    state.orgName = profile.orgName
    state.fba = profile.fba
    state.orgOwner = profile.orgOwner
  },
  SET_ROUTES(state, routes) {
    // setRoutes(routes)
    // state.routes = routes
    setRoutes(routes.menus)
    state.routes = routes.menus
    state.btns = routes.btns
  },
  RESET_ROUTES(state) {
    resetRoutes()
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.sid)
        setToken(data.sid)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response
        commit('SET_PROFILE', data)
        commit('SET_ROUTES', data.menus)
        // this.dispatch('getCustomerType')
        // this.dispatch('getPaymentTerm')
        // this.dispatch('getChannelOptions')
        if (!data.orgOwner) {
          this.dispatch('getCustomerOptions')
        }
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        location.reload()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

